import { getFile, saveFile } from 'src/api/FileApi';
import { pathJoin } from 'src/api/SysApi';
import yaml from 'js-yaml';
import { LocalStorage } from 'quasar';

let ymlPath: string;
export const getYml = (fileName: string): Promise<object> => {
  return new Promise((resolve) => {
    getFile(
      pathJoin(
        getYmlPath() ||
          pathJoin(window.ipcCom.getDirname(), '..', 'config'),
        fileName
      ),
      true
    ).then((r: string) => {
      resolve(yaml.load(r) as object);
    });
  });
};

export const saveYml = (fileName: string, data: object): Promise<string> => {
  return new Promise((resolve) => {
    saveFile(
      pathJoin(
        getYmlPath() ||
          pathJoin(window.ipcCom.getDirname(), '..', 'config'),
        fileName
      ),
      yaml.dump(data)
    ).then((r: string) => {
      resolve(r);
    });
  });
};

export const setYmlPath = (path?: string) => {
  if (!path) {
    pathJoin(window.ipcCom.getDirname(), '..', 'config');
  } else {
    ymlPath = path;
  }
  LocalStorage.set('ymlPath', ymlPath);
};
export const getYmlPath = (): string => {
  return (
    LocalStorage.getItem('ymlPath') ||
    pathJoin(window.ipcCom.getDirname(), '..', 'config')
  );
};
